﻿using System.Collections.Generic;
using MySql.Data.MySqlClient;

namespace Possan.MySQL.Providers
{
	class RoleCache
	{
		private string _connStr;
		private static object _lockobject = new object();
		private static Dictionary<string, string> _idcache = new Dictionary<string, string>();

		public RoleCache(string connectionstring)
		{
			_connStr = connectionstring;
		}

		public string GetIdByName(string role)
		{
			string ret = "";

			lock (_lockobject)
			{
				if (_idcache.ContainsKey(role))
					ret = _idcache[role];
			}

			if (ret != "")
				return ret; 

			using (var conn = new MySqlConnection(_connStr))
			{
				conn.Open();
				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"SELECT r.RoleId FROM aspnet_Roles r on r.LoweredRoleName = @a";
					cmd.Parameters.Add(new MySqlParameter("@a", role.ToLower()));
					using (var rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
							ret = rdr["RoleID"].ToString();
						rdr.Close();
					}
					cmd.Dispose();
				}
				conn.Close();
			}

			if (ret != "")
				lock (_lockobject)
				{
					if (_idcache.ContainsKey(role))
						_idcache[role] = ret;
					else
						_idcache.Add(role, ret);
				}
			
			return ret;
		}
	}
}
